package com.riatimes.manager
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Nick Wong
	 */
	public class MusicManager
	{
		private var url:String;
		private var loopcount:int = 0;
		private var soundChannel:SoundChannel;
		private var sound:Sound;
		private var volumV:Number = .8;
		private var isPauseByNav:Boolean = false;
		public function MusicManager() 
		{
			soundChannel = new SoundChannel(); 
			
		}
		
		public function play(url:String, loop:int = 0):void {
			this.url = url;
			this.loopcount = loop;			
			if(soundChannel) soundChannel.stop();			
			sound = new Sound(new URLRequest(url));
			soundChannel = sound.play(0, 1);
			if(isPauseByNav)soundChannel.soundTransform=new SoundTransform(0);
			soundChannel.addEventListener(Event.SOUND_COMPLETE,__soundCompleteHandle,false,0,true);
		}
		
		
		public function setVolum(v:Number):void {
			this.volumV = v;
			soundChannel.soundTransform=new SoundTransform(v);
		}
		
		public function pause(b:Boolean = false):void {
			if(b)isPauseByNav = true;
			soundChannel.soundTransform=new SoundTransform(0);
		}
		
		public function resume(b:Boolean = false):void {
			if (b) isPauseByNav = false;
			if(!isPauseByNav)
				setVolum(volumV);
		}
		
		private function __soundCompleteHandle(e:Event):void 
		{
			if (loopcount == 0) {
				soundChannel = sound.play(0, 1);
				if(isPauseByNav)soundChannel.soundTransform=new SoundTransform(0);
				soundChannel.addEventListener(Event.SOUND_COMPLETE,__soundCompleteHandle,false,0,true);
			}else if (loopcount == 1) {
				if(soundChannel)
					soundChannel.stop();
			}else {
				loopcount -= 1;
			}
		}
		
		public function playAnotherOnce(url:String):void {
			try{
				new Sound(new URLRequest(url)).play(0, 1);
			}catch(e:Error){}
		}
		
	}

}